$(document).ready(function() {
    
    $("#id_region").change(function(){
        var id_region = parseInt(this.value);
        
        if(id_region > 0) {
            $("#id_district").load("/auction/ajax-districts-reload", {
                id_region: id_region
            }, function(responseText, textStatus) {
                if(textStatus == "success") {
                    this.disabled = false;
                }else {
                    this.disabled = true;
                }
                
                $("#id_town").val(0);
                $("#id_town").attr("disabled", "disabled");
            });
        }else {
            $("#id_district").val(0);
            $("#id_district").attr("disabled", "disabled");
            $("#id_town").val(0);
            $("#id_town").attr("disabled", "disabled");
        }
    });
    
    $("#id_district").change(function(){
        var id_district = parseInt(this.value);
        
        if(id_district > 0) {
            $("#id_town").load("/auction/ajax-town-reload", {
                id_region: $("#id_region").val(),
                id_district: id_district
            }, function(responseText, textStatus) {
                if(textStatus == "success") {
                    if(this.childNodes.length > 1) {
                        this.disabled = false;
                    }else {
                        this.disabled = true;
                    }  
                }else {
                    this.disabled = true;
                }
            });
        }else {
            $("#id_town").val(0);
            $("#id_town").attr("disabled", "disabled");
        }
    });
    
});

